const schedule = require('node-schedule')
const snmpUtil = require('./snmp')
const iptableModel = require('../models/iptable')


// 定义规则
// let rule = new schedule.RecurrenceRule();
// rule.second = [0, 10, 20, 30, 40, 50]; // 每隔 10 秒执行一次
// global.job1 = schedule.scheduleJob('job1',rule,()=>{
//   console.log("job1=========",new Date())
// })
// global.job2 = schedule.scheduleJob('job2',rule,()=>{
//   console.log("job2=========",new Date())
// })
function createJob(jobid, snmpInfo) {
  let rule = new schedule.RecurrenceRule();
  //rule.minute = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55]
  rule.minute = [0,10,20,30,40, 50,]
  //rule.minute = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58]
  //rule.second = [0, 20, 40]; // 每隔 20 秒执行一次
  console.log("开始创建任务：",jobid)
  return schedule.scheduleJob(jobid, rule, async () => {
    //获取SNMP设备的ARP
   // console.log('snmpinfo:',snmpInfo)
   console.log('执行一次任务:',new Date().toLocaleString(),"jobid:",jobid)
    const {ip, port, redKey} = snmpInfo;
    //const {_id: row_id, ips} = ctx.request.body.body
    //console.log(ips)
    var options = {
      port: port,
      retries: 1,
      timeout: 5000,
      backoff: 1.0,
      transport: "udp4",
      trapPort: 162,
      version: snmpUtil.snmp.Version1,
      backwardsGetNexts: true,
      idBitsSize: 32
    };
    var session = snmpUtil.snmp.createSession(ip, redKey, options)
    var rows = []
    //从数据库读取哪些同SNMP的网段需要做任务扫描
    await iptableModel.find({
      'snmpInfo.ip': ip,
      'snmpInfo.port': port,
      'snmpInfo.redKey': redKey,
      'snmpInfo.timeSan': true
    }).exec().then(res => {
     // console.log("数据库需要扫描的数据：",res)
      if (res) rows = res
    })
    snmpUtil.getArp(session).then(back => {
      //console.log("getArp结束返回：",back)
      if(!back.success) return
      //在获取的所有ARP信息表中进行筛选
      back.data.filter(item => {
        //对每个row进行对比存值操作
        for (var i in rows) {
          var {_id: row_id, ips} = rows[i]
          ips.some(function (obj, index, array) {
            //如果当前网段的IP行在ARP中有值，则返回arp行数据,是下面返回item，这里只是判断要不要返回
            if (obj.ip == item.ip) { //arp信息写入数据库
              var arpdata = {'mac': item.mac, 'time': new Date()}
              //如果查到的MAC和原有记录不一至，说明IP被新MAC占用,把原记录放入oldarp记录去
              if (obj.hasOwnProperty('arp') && obj.arp.mac != item.mac)
                iptableModel.findOneAndUpdate({_id: row_id, 'ips._id': obj._id}, {
                  $set: {
                    'ips.$[ip].arp': arpdata,
                    'ips.$[ip].oldarp': obj.arp
                  },
                }, {
                  arrayFilters: [{'ip._id': obj._id}], new: true, // 返回修改后的数据
                }).exec()
              else //直接写新的arp
                iptableModel.findOneAndUpdate({_id: row_id, 'ips._id': obj._id}, {$set: {'ips.$[ip].arp': arpdata},}, {
                  arrayFilters: [{'ip._id': obj._id}], new: true, // 返回修改后的数据
                }).exec()
            }
            return obj.ip == item.ip //条件判断
          })
        }

      })

    })
  })
}

function appStartCheckJob(){
  console.log("appStartCheckJob")
  //1.查IP网段段，看没有打开定时任务的
  iptableModel.find({ 'snmpInfo.timeSan': true}).exec().then(res=>{
    //console.log(res)
    res.filter(item=>{
      if(!global.hasOwnProperty('jobs')) global.jobs = {}
      if(!global.jobs.hasOwnProperty(item.snmpInfo.ip+'_'+item.snmpInfo.port+'_'+ item.snmpInfo.redKey)&&
      item.snmpInfo.ip && item.snmpInfo.port &&  item.snmpInfo.redKey ){
        //如果没有此ip_port_redkey开头的就创建一个任务，有就不管了
        console.log("调用创建1次")
       global.jobs[item.snmpInfo.ip+'_'+item.snmpInfo.port+'_'+item.snmpInfo.redKey]=createJob(item.snmpInfo.ip+'_'+item.snmpInfo.port+'_'+item.snmpInfo.redKey,item.snmpInfo)
      }
    })
  })
  //2.创建任务
}

module.exports.createJob = createJob;
module.exports.appStartCheckJob = appStartCheckJob;
